document.addEventListener('DOMContentLoaded', function() {
    // DOM Elements
    const fileInput = document.getElementById('fileInput');
    const uploadBtn = document.getElementById('uploadBtn');
    const dropArea = document.getElementById('dropArea');
    const progressBar = document.getElementById('progressBar');
    const statusText = document.getElementById('statusText');
    const downloadBtn = document.getElementById('downloadBtn');
    const processAnotherBtn = document.getElementById('processAnotherBtn');
    const uploadSection = document.getElementById('uploadSection');
    const processingSection = document.getElementById('processingSection');
    const downloadSection = document.getElementById('downloadSection');
    const errorSection = document.getElementById('errorSection');
    
    // State
    let currentTaskId = null;
    let processedFilename = null;
    
    // Initialize
    initEventListeners();
    
    function initEventListeners() {
        // File selection
        fileInput.addEventListener('change', handleFileSelect);
        
        // Upload button
        uploadBtn.addEventListener('click', handleUpload);
        
        // Drag & drop
        dropArea.addEventListener('dragover', handleDragOver);
        dropArea.addEventListener('dragleave', handleDragLeave);
        dropArea.addEventListener('drop', handleDrop);
        
        // Process another button
        processAnotherBtn.addEventListener('click', resetUI);
    }
    
    function handleFileSelect(e) {
        if (fileInput.files.length > 0) {
            // Visual feedback
            dropArea.innerHTML = `
                <h5>Selected file:</h5>
                <p>${fileInput.files[0].name}</p>
                <button class="btn btn-sm btn-outline-secondary mt-2" 
                        onclick="event.stopPropagation(); fileInput.value = ''; resetDropArea()">
                    Change File
                </button>
            `;
        }
    }
    
    function resetDropArea() {
        dropArea.innerHTML = `
            <h4>Drag & Drop your video here or click to select</h4>
            <p class="text-muted">Supported formats: MP4, MOV, AVI, MKV (Max 500MB)</p>
            <button class="btn btn-primary mt-3" onclick="document.getElementById('fileInput').click()">
                Select File
            </button>
        `;
    }
    
    function handleUpload() {
        if (fileInput.files.length === 0) {
            showError('Please select a video file first');
            return;
        }
        
        uploadFile(fileInput.files[0]);
    }
    
    function handleDragOver(e) {
        e.preventDefault();
        dropArea.classList.add('highlight');
    }
    
    function handleDragLeave() {
        dropArea.classList.remove('highlight');
    }
    
    function handleDrop(e) {
        e.preventDefault();
        handleDragLeave();
        
        if (e.dataTransfer.files.length > 0) {
            fileInput.files = e.dataTransfer.files;
            uploadFile(e.dataTransfer.files[0]);
        }
    }
    
    function uploadFile(file) {
        // Validate file type
        const validTypes = ['video/mp4', 'video/quicktime', 'video/x-msvideo', 'video/x-matroska'];
        if (!validTypes.includes(file.type)) {
            showError('Please upload a valid video file (MP4, MOV, AVI, MKV)');
            return;
        }
        
        // Show processing UI
        uploadSection.style.display = 'none';
        processingSection.style.display = 'block';
        errorSection.style.display = 'none';
        statusText.textContent = 'Uploading file...';
        
        const formData = new FormData();
        formData.append('file', file);
        
        fetch('/upload', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                throw new Error(data.error);
            }
            
            currentTaskId = data.task_id;
            statusText.textContent = 'Processing video...';
            
            // Start polling for status
            pollTaskStatus();
        })
        .catch(error => {
            showError('Upload failed: ' + error.message);
            resetUI();
        });
    }
    
    function pollTaskStatus() {
        if (!currentTaskId) return;
        
        fetch(`/status/${currentTaskId}`)
        .then(response => response.json())
        .then(data => {
            console.log('[调试] 服务端返回:', data); // 关键调试点
            updateProgress(data);
            
            if (data.state === 'SUCCESS') {
                // Processing complete
                console.log('[调试] 文件路径:', data.result);
                processedFilename = data.result || data.filepath;
                processedFilename = processedFilename.split('/').pop();
                processingSection.style.display = 'none';
                downloadSection.style.display = 'block';
                
                // Set download link
                downloadBtn.href = `/download/${processedFilename}`;
            } else if (data.state === 'FAILURE') {
                throw new Error(data.status || 'Processing failed');
            } else {
                // Continue polling
                setTimeout(pollTaskStatus, 1000);
            }
        })
        .catch(error => {
            showError('Processing error: ' + error.message);
            resetUI();
        });
    }
    
    function updateProgress(data) {
        if (data.progress !== undefined) {
            const progress = Math.round(data.progress);
            progressBar.style.width = `${progress}%`;
            progressBar.textContent = `${progress}%`;
        }
        
        if (data.status) {
            statusText.textContent = data.status;
        }
    }
    
    function showError(message) {
        errorSection.textContent = message;
        errorSection.style.display = 'block';
    }
    
    function resetUI() {
        uploadSection.style.display = 'block';
        processingSection.style.display = 'none';
        downloadSection.style.display = 'none';
        errorSection.style.display = 'none';
        progressBar.style.width = '0%';
        fileInput.value = '';
        resetDropArea();
    }
});
